<template>
  <div class="article-detail-page">
    <div class="container">
      <!-- 左侧操作按钮 (桌面端) -->
      <aside class="left-sidebar desktop-only">
        <ArticleActions
          :comment-count-number="commentCountNumber"
          :detail="article"
          @like="handleLike"
          @collect="handleCollect"
          @fullscreen="handleFullscreen"
          @comment="handleComment"
        />
      </aside>

      <!-- 主内容区 -->
      <main class="article-main">
        <!-- 文章头部 -->
        <div class="article-header">
          <h1 class="article-title">{{ article?.title }}</h1>
          <div class="article-meta">
            <div class="author-info">
              <img :src="headerImg" alt="admin" class="avatar" />
              <div class="author-details">
                <span class="author-name">{{ 'admin' }}</span>
                <ClientOnly>
                  <div class="meta-info">
                    <span class="date">{{
                      article?.updateTime &&
                      dayjs(article?.updateTime).format('YYYY-MM-DD  HH:mm:ss')
                    }}</span>
                    <span class="separator">•</span>
                    <span class="views">{{ article?.readCounts }} 阅读</span>
                    <span class="separator">•</span>
                    <span class="read-time">{{ commentCountNumber }} 评论</span>
                  </div>
                </ClientOnly>
              </div>
            </div>
            <ClientOnly>
              <div class="article-tags">
                <IconTag class="tag-icon" />
                <a-tag v-for="tag in article?.categoryList" :key="tag" color="purple">{{
                  tagsList?.find((item) => +item.id === +tag)?.name
                }}</a-tag>
              </div>
            </ClientOnly>
          </div>
        </div>

        <!-- Markdown 内容 -->
        <div class="markdown-body" v-html="renderedContent"></div>

        <!-- 文章底部 -->
        <div class="article-footer">
          <div class="copyright">
            <p>本文由 <strong>@秋水无痕</strong> 原创发布</p>
            <p>如需转载，请联系作者授权</p>
          </div>
        </div>

        <!-- 评论区域 -->
        <ArticleComments :article-id="id" @comment-count="commentCount" />
      </main>

      <!-- 右侧目录 (桌面端) -->
      <aside class="right-sidebar desktop-only">
        <ArticleToc ref="tocRef" />
      </aside>

      <!-- 移动端抽屉 -->
      <MobileDrawer
        ref="drawerRef"
        placement="right"
        class="mobile-only"
        @like="handleLike"
        @collect="handleCollect"
        @fullscreen="handleFullscreen"
        @comment="handleComment"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, markRaw } from 'vue'
import { useRoute } from 'vue-router'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'github-markdown-css/github-markdown.css'
import 'highlight.js/styles/github.css'
import IconTag from '~/assets/icons/IconTag.vue'
import ArticleActions from './components/ArticleActions.vue'
import ArticleToc from './components/ArticleToc.vue'
import MobileDrawer from './components/MobileDrawer.vue'
import ArticleComments from './components/ArticleComments.vue'
import { getArticleDetail, getTagsList } from '~/api/article'
import headerImg from '@/assets/image/header.png'
import dayjs from 'dayjs'

// 定义文章接口
interface Article {
  title: string
  content: string
  categoryId: string
  readCounts: number
  commentCounts: number
  updateTime: string
  categoryList?: string[]
}

interface Tag {
  id: number
  name: string
}

// 配置 marked
const renderer = markRaw(new marked.Renderer())
marked.use({
  renderer,
  gfm: true,
  breaks: true,
})

const route = useRoute()
const tocRef = ref()
const drawerRef = ref()
const commentCountNumber = ref<number>(0)
// 获取路由中的id
const id = route.params.id as string
// 模拟文章数据
const article = ref<Article>({
  title: '',
  content: '',
  categoryId: '',
  readCounts: 0,
  commentCounts: 0,
  updateTime: '',
  categoryList: [],
})
// 获取分类列表
const tagsList = ref<Tag[]>([])
getTagsList().then((res) => {
  const result: any = res.data.value
  console.log('分类列表', result)
  if (result.code === 200) {
    tagsList.value = result.data
    console.log('分类列表赋值成功', result.data)
  }
})
// 获取文章详情
getArticleDetail(id).then((res) => {
  const result: any = res.data.value
  console.log('文章详情', result)
  if (result.code === 200) {
    const list = result.data.categoryId.split(',')
    result.data.categoryList = list
    article.value = result.data
  }
})
// 渲染 Markdown
const renderedContent = computed(() => {
  if (typeof window === 'undefined' || !article?.value?.content) {
    return ''
  }

  const html = marked(article.value.content) as string
  // 手动处理代码高亮
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = html
  tempDiv.querySelectorAll('pre code').forEach((block) => {
    hljs.highlightElement(block as HTMLElement)
  })
  return tempDiv.innerHTML
})

// 处理操作
const handleLike = () => {
  console.log('点赞')
}

const handleCollect = () => {
  console.log('收藏')
}

const handleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const handleComment = () => {
  console.log('评论')
  // 滚动到评论区
  window.scrollTo({ top: document.querySelector('#comments')?.offsetTop, behavior: 'smooth' })
}
const commentCount = (count: number) => {
  commentCountNumber.value = count
}
onMounted(() => {
  nextTick(() => {
    tocRef.value?.extractToc()
    drawerRef.value?.extractToc()
  })
})
</script>

<style scoped>
.article-detail-page {
  background: #f7fafc;
  min-height: 100vh;
  padding: 24px 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  gap: 24px;
}

/* 左侧操作栏 */
.left-sidebar {
  width: 80px;
  flex-shrink: 0;
}

/* 主内容区 */
.article-main {
  flex: 1;
  max-width: 944px;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 文章头部 */
.article-header {
  margin-bottom: 40px;
  padding-bottom: 24px;
  border-bottom: 2px solid #f7fafc;
}

.article-title {
  font-size: 32px;
  font-weight: 700;
  color: #1a202c;
  margin: 0 0 20px 0;
  line-height: 1.4;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-size: 15px;
  font-weight: 600;
  color: #1a202c;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #a0aec0;
}

.separator {
  color: #cbd5e0;
}

.article-tags {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tag-icon {
  width: 16px;
  height: 16px;
  color: #667eea;
}

/* Markdown 内容样式 */
.markdown-body {
  font-size: 16px;
  line-height: 1.8;
  color: #2d3748;
}

.markdown-body :deep(h2) {
  margin-top: 32px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f7fafc;
  font-size: 24px;
  font-weight: 700;
  color: #1a202c;
}

.markdown-body :deep(h3) {
  margin-top: 24px;
  margin-bottom: 12px;
  font-size: 20px;
  font-weight: 600;
  color: #2d3748;
}

.markdown-body :deep(h4) {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #4a5568;
}

.markdown-body :deep(p) {
  margin-bottom: 16px;
}

.markdown-body :deep(code) {
  background: #f7fafc;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 14px;
  color: #667eea;
}

.markdown-body :deep(pre) {
  background: #2d3748;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 16px 0;
}

.markdown-body :deep(pre code) {
  background: none;
  padding: 0;
  color: #e2e8f0;
}

.markdown-body :deep(ul),
.markdown-body :deep(ol) {
  margin-bottom: 16px;
  padding-left: 24px;
}

.markdown-body :deep(li) {
  margin-bottom: 8px;
}

.markdown-body :deep(blockquote) {
  border-left: 4px solid #667eea;
  padding-left: 16px;
  margin: 16px 0;
  color: #718096;
  font-style: italic;
}

/* 文章底部 */
.article-footer {
  margin-top: 48px;
  padding-top: 24px;
  border-top: 2px solid #f7fafc;
}

.copyright {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.copyright p {
  margin: 4px 0;
  font-size: 14px;
  color: #718096;
}

.copyright strong {
  color: #667eea;
}

/* 右侧目录 */
.right-sidebar {
  width: 280px;
  flex-shrink: 0;
}

/* 响应式 */
.desktop-only {
  display: block;
}

.mobile-only {
  display: none;
}

@media (max-width: 968px) {
  .container {
    flex-direction: column;
    padding: 0 16px;
  }

  .desktop-only {
    display: none;
  }

  .mobile-only {
    display: block;
  }

  .article-main {
    padding: 24px 20px;
  }

  .article-title {
    font-size: 24px;
  }

  .article-meta {
    flex-direction: column;
    align-items: flex-start;
  }

  .markdown-body {
    font-size: 15px;
  }

  .markdown-body :deep(h2) {
    font-size: 20px;
  }

  .markdown-body :deep(h3) {
    font-size: 18px;
  }

  .markdown-body :deep(pre) {
    padding: 12px;
    font-size: 13px;
  }
}
</style>
